<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-purple-dark">
          <!--  1、顶部搜索框，下拉列表，查询按钮，重置  -->
          <el-form
              :inline="true"
              :model="formInline"
              class="demo-form-inline"
              style="margin-top: 0px; margin-left: 25px;line-height: 25px">
            <el-form-item label="申请人名称" ref="formRef">
              <el-input v-model="formInline.name" placeholder="请输入名称"></el-input>
            </el-form-item>
            <el-form-item label="职务">
              <el-select v-model="form.job" clearable placeholder="请选择职务">
                <el-option label="普通医生" value="普通医生"></el-option>
                <el-option label="管理员" value="管理员"></el-option>
                <el-option label="药管师" value="药管师"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" plain @click="select">查询</el-button>
              <el-button type="danger" plain @click="resetForm('formInline')">重置</el-button>
            </el-form-item>
          </el-form>

          <!--  2、请假单列表  -->
          <el-card class="box-card-leave" style="margin-left: 25px">
            <el-table :data="tableData" border style="width: 100%"
                      :cell-style="{ padding: '8px', 'text-align': 'center' }">
              <el-table-column prop="id" label="假单编号" width="100"></el-table-column>
              <el-table-column prop="name" label="申请人" width="100"></el-table-column>
              <el-table-column prop="gender" label="性别" width="100"></el-table-column>
              <el-table-column prop="data_birth" label="年龄" width="100"></el-table-column>
              <el-table-column prop="mobile" label="联系电话" width="100"></el-table-column>
              <el-table-column prop="department_name" label="所属部门" width="100"></el-table-column>
              <el-table-column prop="department_type" label="部门类型" width="100"></el-table-column>
              <el-table-column prop="job" label="职位" width="100"></el-table-column>
              <el-table-column prop="leave_category" label="请假类型" width="100"></el-table-column>
              <el-table-column prop="leave_reason" label="请假原因" width="100"></el-table-column>
              <el-table-column prop="leave_time" label="申请时间" width="100"></el-table-column>
              <el-table-column prop="leave_days" label="请假天数" width="100"></el-table-column>
              <el-table-column prop="start_time" label="开始时间" width="100"></el-table-column>
              <el-table-column prop="leave_type_name" label="假单状态" width="100">
                <template slot-scope="scope">
                  <el-tag type="danger" v-if="scope.row.leave_type_name === '待批准'" effect="dark">未批准</el-tag>
                  <el-tag type="success" v-if="scope.row.leave_type_name === '已批准'" effect="dark">已批准</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="批准申请/修改假单/拒绝申请">
                <template slot-scope="scope">
                  <el-button el-button type="primary" icon="el-icon-search" circle @click="approval(scope.row)"
                             size="small"></el-button>

                  <el-button el-button type="info" icon="el-icon-s-data" circle @click="edit(scope.row),(drawer = true)"
                             size="small"></el-button>

                  <el-button el-button type="danger" icon="el-icon-delete" circle @click="refuse(scope.row)"
                             size="small"></el-button>
                  <!--            <el-button type="danger" icon="el-icon-delete" circle @click="showRefuseDialog(scope.row)"-->
                  <!--                       size="small"></el-button>-->
                </template>
              </el-table-column>
            </el-table>
          </el-card>
          <!--    <el-button type="text" >打开嵌套表单的 Dialog</el-button>-->

          <!-- 3、拒绝删除单个假单模块  -->
          <el-dialog title="发送短信" :visible.sync="dialogFormVisible">
            <el-form :model="form">
              <el-form-item label="手机号" :label-width="formLabelWidth">
                <el-input v-model="form.mobile" autocomplete="off" disabled></el-input>
              </el-form-item>
              <el-form-item label="拒绝原因" :label-width="formLabelWidth">
                <el-input type="textarea" v-model="form.reason" autocomplete="off" :rows="5" maxlength="30"
                          show-word-limit></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <!--<el-button type="primary" @click="send = true">确 定</el-button>-->
              <el-button type="primary" @click="is_tetx">确 定</el-button>

            </div>
          </el-dialog>

          <!--4、底部组件          -->
          <div style="margin-bottom: 20px">
            <nobr>
              <!--   批量删除模块 -->
              <el-button
                  type="danger"
                  plain
                  @click="batchDelete"
                  style="position: absolute; margin-left: 10px; margin-top: 25px; margin-bottom: 30px"
                  :disabled="multipleSelection.length === 0">批量删除
              </el-button>
              <!--  前端分页模块    -->
              <div class="course_pagination block">
                <!--                <el-pagination-->
                <!--                    background-->
                <!--                    layout="prev, pager, next,total"-->
                <!--                    :total=departmentPageDto-->
                <!--                    :page-size=filter.size-->
                <!--                    style="position: absolute; margin-left: 700px; margin-top: 30px"-->
                <!--                    @current-change="handleCurrentChange">-->
                <!--                </el-pagination>-->
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="filter.page"
                    :page-sizes="[2, 3, 5, 10]"
                    :page-size="filter.size"
                    layout="sizes, prev, pager, next"
                    :total="course_total">
                </el-pagination>
              </div>
            </nobr>
          </div>

          <!--   5、编辑假单  完成   -->
          <el-drawer title="编辑假单" :visible.sync="drawer" :direction="direction" :before-close="handleClose">
            <el-form ref="form" :model="form" label-width="80px" style="position: absolute; margin-left: 30px;
          margin-top: 30px;width: 400px;">
              <el-form-item label="假单编号">
                <el-input v-model="form.id" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="申请人">
                <el-input v-model="form.name" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="所属部门">
                <el-input v-model="form.department_name" :disabled="true"></el-input>
              </el-form-item>
              <!--   4、下拉列表   -->
              <el-form-item label="请假类型">
                <el-select v-model="form.leave_category" clearable placeholder="请选择">
                  <el-option label="公假" value="公假"></el-option>
                  <el-option label="婚假" value="婚假"></el-option>
                  <el-option label="丧假" value="丧假"></el-option>
                  <el-option label="产假" value="产假"></el-option>
                  <el-option label="年假" value="年假"></el-option>
                  <el-option label="探亲假" value="探亲假"></el-option>
                  <el-option label="病假" value="病假"></el-option>
                  <el-option label="其他" value="其他"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="请假原因">
                <el-input v-model="form.leave_reason" type="textarea"></el-input>
              </el-form-item>
              <el-form-item label="请假时间" prop="absenceTime" class="demonstration">
                <el-date-picker v-model="form.absenceTime" type="daterange" placeholder="选择日期"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期" @blur="count">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="__天" prop="totalTime">
                <el-input v-model="form.totalTime" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submit">提交编辑</el-button>
              </el-form-item>
            </el-form>
          </el-drawer>
        </div>
      </el-col>
    </el-row>

  </div>
</template>

<script>
export default {

  name: 'LeaveManage',
  data() {
    return {

      // 在使用注入的组件中
      inject: ['reload'],
      row: "",
      course_total: 0,   // 当前总数量
      filter: {
        course_category: 0, // 当前用户选择的课程分类，刚进入页面默认为全部，值为0
        ordering: "orders",    // 数据的排序方式，默认值是orders，表示对于id进行降序排列
        size: 2,       // 单页数据量
        page: 1,
      },
      formInline: {
        name: "",
        category: "",
        deptType: "",
      },
      form: {
        id: '',
        name: '',
        department_name: '',
        leave_category: '',
        leave_reason: '',
        absenceTime: '',
        totalTime: '',
        reason: '',
        mobile: '',
      },
      // departmentPageDto: {},
      departmentPageDto: null,
      user: {},
      tableData: [],
      multipleSelection: [],
      jobClassification: [],
      jobType: [],
      drawer: false,
      direction: "rtl",
      dialogFormVisible: false,
      formLabelWidth: '120px',
      send: true,
    };
  },
  created() {
    // this.$axios.get(this.$settings.BASE_URL + 'system/leave/').then(response => {
    this.$axios.get(`${this.$settings.BASE_URL}leaveplatform/leave/`).then(response => {
      console.log(response.data.results)
      console.log('我在这哦')
      console.log(response.data.count)
      this.tableData = response.data.results
      this.departmentPageDto = response.data.count
    })
    // this.user = this.$getSessionStorage("user");
    // this.user_type = this.$getSessionStorage("user_type");
    this.user = "岳";
    // this.user = window.sessionStorage.getItem('user');
    // this.user_type = window.sessionStorage.getItem('user_type');
    this.user_type = "管理员";
    // this.user_type = "医生";
    console.log(this.user_type, '<<<<<<<<')
  },
  methods: {
    handleCurrentChange(pageNumber) {
      this.select(pageNumber);
    },
    //
    edit(row) {
      console.log(row, '>>>>>>>>>>>')
      if (this.user_type === '管理员') {
        this.form = row;
        console.log(this.form, '........>>>>>')
        // console.log('err')
      } else {
        this.$message({
          message: "很抱歉,您没有权限编辑假单",
          type: 'warning',
          duration: 1000
        })
      }
    },

    //send变化
    send_temp() {
      this.send = !this.send
    },
    is_tetx() {
      if (this.form.reason.length !== 0) {
        console.log(this.form.reason, '___===>>>>>')
        Promise.all([
          this.$axios.delete(`${this.$settings.BASE_URL}leaveplatform/leave/${this.row.id}/`),
          this.$axios.post(`http://127.0.0.1:8000/api/v1/leaveplatform/send_mobile/`, {
            'mobile': this.row.mobile,
            'reason': this.form.reason
          })
        ]).then(([deleteResponse, sendResponse]) => {
          console.log(deleteResponse, sendResponse);
          this.$message({
            message: `删除假单成功`,
            type: 'success',
            duration: 1000
          });
          window.setTimeout(() => {
            this.reload();
          }, 1000);
          this.dialogFormVisible = false;
          if (sendResponse.data.code === 100) {
            this.$message({
              message: '发送成功',
              type: 'success',
              duration: 1000
            });
          }
        }).catch((error) => {
          console.error(error);
          this.$message({
            message: '删除失败',
            type: 'warning',
            duration: 1000
          });
        });
      } else {
        this.$message({
          message: '请填写拒绝原由666',
          type: 'warning',
          duration: 1000
        });
      }
    },
    refuse(row) {
      if (this.user_type === '管理员') {
        this.$confirm("确认删除此假单？").then((_) => {
          console.log(row)
          console.log(row.id);
          this.row = row
          //axios通过id删除药品
          this.dialogFormVisible = true
          this.form.mobile = row.mobile
          if (this.send) {
          }
        })
      } else {
        this.$message({
          message: '很抱歉，你没有权限删除假单',
          type: 'warning',
          duration: 1000
        });
      }
    },

    approval(row) {
      this.$confirm("确定要批准该申请吗？")
          .then((_) => {
            row.leave_type = 2;
            // this.$axios.put(`${this.$settings.BASE_URLS}leaveplatform/leave/${row.id}/`, row).then(response => {
            this.$axios.put(`${this.$settings.BASE_URL}leaveplatform/leave/${row.id}/`, row).then(response => {
              this.$message({
                message: '您已批准该假单',
                type: 'success',
                duration: 1000
              });

              // 在这里定义一个指向组件实例的变量 vm
              const vm = this;

              window.setTimeout(() => {
                // 使用 vm.reload() 调用组件的 reload 方法
                vm.reload();
              }, 1000);
            });
          })
          .catch((_) => {
            console.log(row);
          });
    },
    reload() {
      // 重新加载页面的逻辑
      window.location.reload();
    },
    submit() {
      console.log(this.form)
      // console.log(this.form)
      let _this = this
      let d = new Date(this.form.absenceTime[0])
      let start_time = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()
      this.form.leave_days = this.form.totalTime
      this.form.start_time = start_time
      this.$delete(this.form, 'totalTime')
      this.$delete(this.form, 'absenceTime')
      // this.$axios.put(this.$settings.BASE_URL + `system/leave/${this.form.id}/`, this.form).then((Response) => {
      this.$axios.put(`${this.$settings.BASE_URL}leaveplatform/leave/${this.form.id}/`, this.form).then((Response) => {
        this.$message({
          message: '编辑成功',
          type: 'success',
          duration: 1000
        })
        window.setTimeout(function () {
          _this.reload();
        }, 1000)
      }).catch((error) => {
        console.error(error);
        alert("编辑假单失败");
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
          .then((_) => {
            done();
            location.reload()
          })
          .catch((_) => {
          });
    },
    resetForm(formName) {
      location.reload();
    },
    batchDelete() {
      if (this.user_type === "管理员") {
        if (this.multipleSelection.length === 0) {
          alert("至少选择一条数据进行批量删除");
        } else {
          this.$confirm("确认批量删除假单？")
              .then((_) => {
                //axios批量删除请求
                this.$axios
                    .post(
                        "/job/removejobBatch",
                        this.multipleSelection
                    )
                    .then((Response) => {
                      alert("批量删除成功");
                    })
                    .catch((error) => {
                      console.error(error);
                    });
              })
              .catch((_) => {
              });
        }
      } else {
        this.$message({
          message: "很抱歉,您没有权限批量删除药品",
          type: 'warning',
          duration: 1000
        })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(val);
    },

    select() {
      let name = this.formInline.name
      console.log(this.formInline.name, "===>>>")
      // console.log(name, '---->>>>')
      if (name.length === 0 || this.form.job.length === 0) {
        this.$message({
          message: '请在框中输入或选择内容',
          type: 'warning',
          duration: 1000
        })
      } else {
        // this.$axios.get(this.$settings.BASE_URL + `system/leave/?name=${name}` + '&' + `job=${this.form.job}`).then(response => {
        this.$axios.get(`${this.$settings.BASE_URL}leaveplatform/leave/?name=${name}&job=${this.form.job}`).then(response => {
          console.log(response.data.results)
          this.tableData = response.data.results
        }).catch(() => {
          this.$message({
            message: '出现异常',
            type: 'warning',
            duration: 1000
          })
        })
      }

    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex === 1) {
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    }
    ,


    daysBetween(start_time, end_time) {
      var day = 0
      var OneMonth = start_time.substring(5, start_time.lastIndexOf('-'));
      var OneDay = start_time.substring(start_time.length, start_time.lastIndexOf('-') + 1);
      var start_day = Number(OneDay.substring(0, OneDay.indexOf(' ')))
      // var OneYear = start_time.substring(0, start_time.indexOf('-'));
      //
      var TwoMonth = end_time.substring(5, end_time.lastIndexOf('-'));
      var TwoDay = end_time.substring(end_time.length, end_time.lastIndexOf('-') + 1);
      var end_day = Number(TwoDay.substring(0, TwoDay.indexOf(' ')))
      // var TwoYear = end_time.substring(0, end_time.indexOf('-'));
      if (TwoMonth == OneMonth) {
        day = end_day - start_day
      } else {
        let end = end_day + 30
        day = end - start_day
      }
      return day
    }
    ,
    count() {
      var d = new Date(this.form.absenceTime[0]);
      let start_time = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
      var d2 = new Date(this.form.absenceTime[1]);
      let end_time = d2.getFullYear() + '-' + (d2.getMonth() + 1) + '-' + d2.getDate() + ' ' + d2.getHours() + ':' + d2.getMinutes() + ':' + d2.getSeconds()
      let a = this.daysBetween(start_time, end_time)
      this.form.totalTime = a
    }
    ,
  }
  ,
}
;
</script>

<style>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card-leave {
  width: 1600px;
}

.el-main {
  line-height: 0px;
}

.course_pagination {
  margin-top: 60px;
  text-align: center;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #909399;
}
</style>






